package com.ybkj.daijia.api.driver.v1;

import com.ybkj.daijia.api.driver.ErrorConstant;
import com.ybkj.daijia.api.driver.SecurityUtils;
import com.ybkj.daijia.api.driver.transport.ResultTransport;
import com.ybkj.daijia.server.mc.Passenger;
import com.ybkj.daijia.server.model.Driver;
import com.ybkj.daijia.server.model.PhoneRecord;
import com.ybkj.daijia.server.service.DriverService;
import com.ybkj.daijia.server.service.MemberAccountService;
import com.ybkj.daijia.server.service.MemberService;
import com.ybkj.daijia.server.service.PhoneRecordService;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 客户工作车相关
 *
 * @author bo
 */
@Controller("PhoneRecordController")
@RequestMapping(value = "driver/api/rest/v1")
public class PhoneRecordController {

    private static final Logger logger = LoggerFactory.getLogger(PhoneRecordController.class);

    @Autowired
    private PhoneRecordService phoneRecordService;
    @Autowired
    private DriverService driverService;
    @Autowired
    private MemberService memberService;
    @Autowired
    private MemberAccountService memberAccountService;


    /**
     * 保存通话记录
     *
     * @param appKey
     * @param token     token令牌
     * @param timestamp 时间戳
     * @return
     */
    @RequestMapping(value = "savePhoneRecord", method = RequestMethod.POST)
    public @ResponseBody
    ResultTransport savePhoneRecord(Long driverId, String phone, Integer phoneType, Long phoneDate,
        Long phoneTime, String appKey, String token, String timestamp) {

        logger.debug(
            "recv driverId:{},phone:{},phoneType:{},phoneDate:{},phoneTime:{}, appKey:{},token:{},timestamp:{}",
            driverId, phone, phoneType, phoneDate, phoneTime, appKey, token, timestamp);

        if (null == driverId || StringUtils.isBlank(phone) || null == phoneType || null == phoneDate
            || null == phoneTime || SecurityUtils.isBlank(appKey, token, timestamp)) {
            return ResultTransport.getErrorBy(ErrorConstant.PARAM_ERROR);
        }

        if (!StringUtils.isNumeric(timestamp) || !SecurityUtils
            .checkTimestamp(Long.parseLong(timestamp))) {
            return ResultTransport.getErrorBy(ErrorConstant.TIMESTAMP_ERROR);
        }
        List<String> params = new LinkedList<String>();
        params.add(String.valueOf(driverId));
        params.add(String.valueOf(phone));
        params.add(String.valueOf(phoneType));
        params.add(String.valueOf(phoneDate));
        params.add(String.valueOf(phoneTime));
        params.add(timestamp);
        params.add(appKey);

        if (!SecurityUtils.checkToken(params, token)) {
            return ResultTransport.getErrorBy(ErrorConstant.TOKEN_ERROR);
        }
        Driver driver = driverService.findOne(driverId);
        if (null == driver) {
            return ResultTransport.getErrorBy(ErrorConstant.DRIVER_NOT_EXISTS);
        }

        Passenger passenger = memberService.findOnePassengerByPhone(phone);
        if (null == passenger) {
            return ResultTransport.getErrorBy(ErrorConstant.MEMBER_NOT_EXISTS);
        }

        try {

            if (phoneTime > 0) {

                SimpleDateFormat formatter = com.ybkj.daijia.constant.DateConstant.DATE_TIME;
                String time = formatter.format(new Date(phoneDate));

                List<PhoneRecord> theSame = phoneRecordService
                    .findByDriverAndPhoneDate(driver.getId(), time);
                if (CollectionUtils.isEmpty(theSame)) {
                    PhoneRecord phoneRecord = new PhoneRecord();
                    phoneRecord.setDriverId(driver.getId());
                    phoneRecord.setDriverName(driver.getRealname());
                    phoneRecord.setDriverPhone(driver.getPhone());
                    phoneRecord.setDriverCompanyId(driver.getCompanyId());
                    phoneRecord.setMemberId(passenger.getId());
                    phoneRecord.setMemberName(passenger.getName());
                    phoneRecord.setMemberPhone(phone);
                    phoneRecord.setMemberCompanyId(passenger.getCompanyId());
                    phoneRecord.setPhoneType(phoneType);
                    phoneRecord.setPhoneDate(new Date(phoneDate));
                    phoneRecord.setPhoneTime(phoneTime);
                    phoneRecordService.insertRecord(phoneRecord);
                }
            }

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstant.SUCCESS);

            return instance;

        } catch (Exception e) {
            logger.error("api v1 driver savePhoneRecord error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstant.SERVER_ERROR);
        }

    }

}
